/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.jwt.core;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.autoconfigure.jwt.TokenProperties;
import cn.star.framework.autoconfigure.security.SecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Jwt Token<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
@Component
public class JwtTokenProvider {
  private final SecretKey key;
  private final TokenProperties token;
  private final SecurityProperties security;

  public JwtTokenProvider(TokenProperties token, SecurityProperties security) {
    this.token = token;
    this.security = security;
    this.key = Keys.hmacShaKeyFor(token.getSecretKey().getBytes(StandardCharsets.UTF_8));
  }

  /**
   * 生成 Token
   *
   * @param subject 主题
   * @return
   */
  public String token(String subject) {
    return this.token(subject, null);
  }

  /**
   * 生成 Token
   *
   * @param subject 主题
   * @param claims 负载
   * @return
   */
  public String token(String subject, Map<String, Object> claims) {
    return this.token(subject, null, claims);
  }

  private Map<String, Object> wrapper(Map<String, Object> claims) {
    Map<String, Object> wClaims = new HashMap<>(1);
    if (CollectionUtil.isNotEmpty(claims)) {
      wClaims.putAll(claims);
    }
    // 防止生成不唯一的Token，高并发会出现
    wClaims.put("Id_", IdUtil.simpleUUID());

    return wClaims;
  }

  /**
   * 生成 Token
   *
   * @param subject 主题
   * @param issuer 发布者
   * @param claims 负载
   * @return
   */
  public String token(String subject, String issuer, Map<String, Object> claims) {
    Date now = new Date();
    JwtBuilder builder = Jwts.builder();
    // 主题
    builder.subject(subject);
    // 负载
    this.wrapper(claims).forEach(builder::claim);
    // 发布者
    if (StrUtil.isNotBlank(issuer)) {
      builder.issuer(issuer);
    }
    // 发布时间
    builder.issuedAt(now);
    // 过期时间
    if (token.getTtl() > 0) {

      builder.expiration(new Date(now.getTime() + token.getTtl()));
    }
    // 签名
    builder.signWith(key, Jwts.SIG.HS256);

    // 包装
    return this.wrapper(builder.compact(), false);
  }

  /**
   * 解析 Token
   *
   * @param token {@link #token(String, String, Map)}生成的Token
   * @return
   */
  public Jws<Claims> parse(String token) {
    String w = this.wrapper(token, true);
    return Jwts.parser().verifyWith(key).build().parseSignedClaims(w);
  }

  /**
   * Token包装
   *
   * @param token 原始Token
   * @param parse true表示解析，否则表示生成
   * @return
   */
  private String wrapper(String token, boolean parse) {
    String prefix = this.token.getPrefix();
    if (StrUtil.isNotBlank(prefix)) {
      if (parse) {
        return token.startsWith(prefix) ? token.substring(prefix.length()) : token;
      } else {
        return prefix + token;
      }
    } else {
      return token;
    }
  }

  /**
   * 从请求中获取Token数据
   *
   * @param request
   * @return
   */
  public String getAccessToken(HttpServletRequest request) {
    String name = this.token.getName();
    // request header
    if (StrUtil.isNotBlank(request.getHeader(name))) {
      return request.getHeader(name);
    }

    // request parameter
    if (StrUtil.isNotBlank(request.getParameter(name))) {
      return request.getParameter(name);
    }

    // cookies
    Cookie[] cookies = request.getCookies();
    if (ArrayUtil.isNotEmpty(cookies)) {
      for (Cookie cookie : cookies) {
        if (name.equals(cookie.getName()) && StrUtil.isNotBlank(cookie.getValue())) {
          return cookie.getValue();
        }
      }
    }

    throw new RuntimeException("Not found Token for header/parameter/cookie");
  }

  /**
   * 刷新Token
   *
   * @param token 原始Token
   * @return
   */
  public String refresh(String token) {
    return this.refresh(token, this.token.getTtl());
  }

  /**
   * 获取{@link Claims}<br>
   * 过期的Token的Claims也能获取
   *
   * @param token 原始Token
   * @return
   */
  public Claims parseClaims(String token) {
    try {
      return this.parse(token).getPayload();
    } catch (ExpiredJwtException e) {
      log.warn(e.getMessage());
      return e.getClaims();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 刷新Token
   *
   * @param token 原始Token
   * @param ttl 延长时间，单位：毫秒
   * @return
   */
  public String refresh(String token, long ttl) {
    Claims claims = this.parseClaims(token);
    Date now = new Date();
    Date exp = new Date(now.getTime() + ttl);
    JwtBuilder builder =
        Jwts.builder().claims(claims).issuedAt(now).expiration(exp).signWith(key, Jwts.SIG.HS256);

    return this.wrapper(builder.compact(), false);
  }

  /**
   * 获取Token过期时间
   *
   * @param token
   * @return
   */
  public long getTokenExpiredTimeMillis(String token) {
    try {
      Date now = new Date();
      Date exp = this.parse(token).getPayload().getExpiration();

      return exp.getTime() - now.getTime();
    } catch (Exception e) {
      // Token 过期
      log.warn(e.getMessage());
      return -127L;
    }
  }

  /**
   * 判断Token是否过期
   *
   * @param token
   * @return
   */
  public boolean isTokenExpired(String token) {
    return this.getTokenExpiredTimeMillis(token) <= 0;
  }
}
